import datetime
import time

from django.http import JsonResponse
from django.shortcuts import render
import json
# Create your views here.
from django.views import View
from requests import session
from django.utils import timezone
from apps.homes.models import House, HouseImage
from apps.orders.models import Order
from apps.orders.tests import compare_time
from apps.users.models import User
from ihome_pro.utils.LoginRequireJson import LoginRequiredJsonMixin
from django.conf import settings


class AddOrderView(LoginRequiredJsonMixin, View):

    # 添加订单
    def post(self, request):

        # 接收参数
        dict = json.loads(request.body.decode())
        house_id = dict.get('house_id')  # 房屋id
        start_date = dict.get('start_date')  # 开始日期
        end_date = dict.get('end_date')  # 结束时间

        # 检验参数
        if not all([house_id, start_date, end_date]):
            return JsonResponse({"errno": 4103, 'errmsg': '参数错误'})

        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({"errno": 4001, 'errmsg': '数据库查询错误'})

        if start_date > end_date:
            return JsonResponse({"errno": 4103, 'errmsg': '参数错误'})

        # 判断是不是自己下的单
        try:
            user = House.objects.get(id=house_id).user
        except Exception as e:
            return JsonResponse({"errno": 4001, 'errmsg': '数据库查询错误'})

        # 一个用户对应多个订单（一查多）
        # TODO
        orders = Order.objects.filter(house_id=house_id, status__in=[Order.ORDER_STATUS['WAIT_ACCEPT']])
        if request.user == user:
            return JsonResponse({"errno": 4201, 'errmsg': '房东不能下自己的单'})
        st = datetime.datetime.date(datetime.datetime.strptime(start_date, '%Y-%m-%d'))
        en = datetime.datetime.date(datetime.datetime.strptime(end_date, '%Y-%m-%d'))
        day = (en - st).days
        # TODO :判断逻辑有误
        if house.max_days != 0:
            if house.max_days < day or house.min_days > day:
                return JsonResponse({"errno": 4201, 'errmsg': '请求天数不在范围内'})
        else:

            if house.min_days > day:
                return JsonResponse({"errno": 4201, 'errmsg': '请求天数不在范围内'})

        # 判断在时间段内，房屋是否被预定
        # if house.order_count >= 1 :
        #     return JsonResponse({"errno":4103,'errmsg':'房屋已经被预定'})

        # for order in orders:
        #     if order.begin_date == st and order.end_date == en:
        #         return JsonResponse({"errno" :4001 ,'errmsg' :'房间已经被预定'})
        # TODO: 时间交叉即为冲突
        for order in orders:
            start_date1 = order.begin_date
            end_date1 = order.end_date
            # 判断房子在日期内有没有被人预定
            start_date1 = str(start_date1)
            end_date1 = str(end_date1)
            result = compare_time(start_date1, end_date1, start_date, end_date)
            if result == 'NG':
                return JsonResponse({
                    'errno': 4001,
                    'errmsg': '房子已经被订了'})
        # 新增订单
        order = Order.objects.create(
            user=request.user,
            house_id=house_id,
            begin_date=st,
            end_date=en,
            days=day,
            house_price=house.price,
            amount=int(house.price) * int(day),
            status=Order.ORDER_STATUS['WAIT_ACCEPT'],

        )

        return JsonResponse({"errno": 0,
                             'errmsg': '下单成功',
                             'data': {
                                 "order_id": order.id
                             }})


    # 获取订单列表
    def get(self, request):

        role = request.GET.get('role')
        user = request.user

        if role == 'custom':
            # 登录的是客户----》查看我的订单
            # 一个用户对应多个订单（一查多）
            order_list = Order.objects.filter(user=user)

            orders = []

            for order in order_list:
                orders.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time.strftime("%Y-%m-%d"),
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": order.house.index_image_url,
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": Order.ORDER_STATUS_ENUM[order.status],
                    "title": order.house.title
                })

        else:
            # 登录的是房东---》查看我的房屋
            # 一个房东对应多个房间
            order_list = Order.objects.filter(house__user=user)

            orders = []
            for order in order_list:
                orders.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time.strftime("%Y-%m-%d"),
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": order.house.index_image_url,
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": Order.ORDER_STATUS_ENUM[order.status],
                    "title": order.house.title
                })

        return JsonResponse({
            "errmsg": "OK",
            "errno": "0",
            'data': {'orders': orders}
        })



# 接单和拒单(房东)
class OrdersStatusView(LoginRequiredJsonMixin, View):

    def put(self, request, order_id):

        dict = json.loads(request.body)
        '''
         $.ajax({
                    url: host + "/api/v1.0/orders/"+orderId+"/status",
                    type:"PUT",
                    data:JSON.stringify(data),
        '''

        '''
        {{if "COMPLETE" == order.status}}
        <li>我的评价： {{order.comment}}</li>
        {{else if "REJECTED" == order.status}}
        <li>拒单原因： {{order.comment}}</li>
        '''
        action = dict.get("action")
        reason = dict.get('reason')

        if action == 'accept':
            a_order = Order.objects.get(id=order_id)
            a_order.status = Order.ORDER_STATUS['WAIT_COMMENT']
            a_order.house.order_count += 1
            a_order.house.save()
            a_order.save()
            return JsonResponse({"errno": 0, 'errmsg': '房东已接单'})
        else:  # 拒单
            if not reason:
                return JsonResponse({"errno": 4103, 'errmsg': '缺少必传参数'})
            a_order = Order.objects.get(id=order_id)
            a_order.status = Order.ORDER_STATUS['REJECTED']
            a_order.comment = reason  # 拒单原因
            a_order.save()
            return JsonResponse({"errno": 0, 'errmsg': '拒单成功'})


# 评论订单（房客）
class OrderCommentView(LoginRequiredJsonMixin, View):

    def put(self, request, order_id):

        # 订单的评论信息或者拒单原因

        comment = json.loads(request.body).get('comment')

        if request.user == 'custom':  # 房客状态（待评价）
            a_order = Order.objects.get(id=order_id)
            a_order.status = Order.ORDER_STATUS['WAIT_COMMENT']
            a_order.comment = comment
            a_order.save()
            return JsonResponse({"errno": 0, 'errmsg': '发表评价成功'})
        else:
            # 房东状态（已接单）
            c_order = Order.objects.get(id=order_id)
            if c_order.status == Order.ORDER_STATUS['WAIT_COMMENT']:
                c_order.comment = comment
                c_order.status = Order.ORDER_STATUS['COMPLETE']
                c_order.save()
                return JsonResponse({"errno": 0, 'errmsg': '已接单'})
            else:
                # 房东拒单，填写拒单原因
                c_order.comment = comment
                c_order.status = Order.ORDER_STATUS['REJECTED']
                c_order.save()
                return JsonResponse({"errno": 0, 'errmsg': '拒单成功'})
